//
//  KeychainManager.swift
//  Lover
//
//  Created by 冯俊武 on 2024/8/11.
//

import Foundation
import Security

struct KeychainManager {
    
    static let shared = KeychainManager()
    
    private let account = "uniqueID"
    
    private init() {}
    
    // 生成并存储 UUID
    func generateAndStoreUUID() -> String? {
        let uuidString = UUID().uuidString
        let success = storeUUIDInKeychain(uuid: uuidString)
        return success ? uuidString : nil
    }
    
    // 从钥匙串中存储 UUID
    private func storeUUIDInKeychain(uuid: String) -> Bool {
        let keychainQuery: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: account,
            kSecValueData as String: uuid.data(using: .utf8)!,
            kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked
        ]
        
        // 先删除之前的值（如果存在）
        SecItemDelete(keychainQuery as CFDictionary)
        
        // 添加新值
        let status = SecItemAdd(keychainQuery as CFDictionary, nil)
        return status == errSecSuccess
    }
    
    // 从钥匙串中读取 UUID
    func retrieveUUID() -> String? {
        let keychainQuery: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: account,
            kSecReturnData as String: kCFBooleanTrue!,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        
        var dataTypeRef: AnyObject? = nil
        let status: OSStatus = SecItemCopyMatching(keychainQuery as CFDictionary, &dataTypeRef)
        
        if status == errSecSuccess {
            if let data = dataTypeRef as? Data {
                return String(data: data, encoding: .utf8)
            }
        }
        return nil
    }
    
    // 删除存储的 UUID
    func deleteUUID() -> Bool {
        let keychainQuery: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: account
        ]
        
        let status = SecItemDelete(keychainQuery as CFDictionary)
        return status == errSecSuccess
    }
}

